<template>
  <view class="bg-white rounded-[28rpx] p-[32rpx] shadow-md relative flex flex-col hover:shadow-lg transition-all duration-300">
    <view>
      <view class="order-header flex justify-between mb-[16rpx] items-start">
        <view class="order-title text-[28rpx] font-bold flex-1 text-[#222]">{{ item.position_name }} </view>
        <view class="text-[22rpx] px-[20rpx] py-[8rpx] rounded-[16rpx] font-medium bg-gradient-to-r from-[#e3f2fd] to-[#bbdefb] text-[#2196F3]">
          {{ change(item) }}
        </view>
      </view>

      <view class="item-meta flex mb-[12rpx] flex-wrap gap-x-[16rpx] gap-y-[8rpx]">
        <view class="meta-item flex items-center text-[22rpx] text-[#666]">
          <IconFont name="locationg3" class="mr-[8rpx] text-[#165DFF]" size="12" />
          <text>{{ item.location }}</text>
        </view>
        <view class="meta-item flex items-center text-[22rpx] text-[#666]">
          <IconFont font-class-name="iconfont" class-prefix="icon" name="building" class="text-blue-500 text-[40rpx] mr-1" size="12" />
          <text>{{ item.corporate_name }}</text>
        </view>
      </view>
      <view class="item-footer flex flex-col mt-[16rpx]">
        <view class="grid grid-cols-1 gap-[16rpx] mb-[18rpx] text-[24rpx]">
          <view class="flex gap-2">
            <span class="text-[#999]">录用人数</span>
            <span class="text-[#52c41a] font-bold">{{ item.number }}人</span>
          </view>
          <view class="text-[24rpx] text-[#666]">职位描述：{{ item.description }}</view>
        </view>

        <view class="flex flex-wrap gap-[16rpx] mb-[18rpx] text-[24rpx] text-[#666] justify-between">
          <view>要求：{{ item.experience }}</view>
          <view>
            日薪：<text class="text-[#ff0000]">¥{{ item.salary }}</text>
          </view>
        </view>

        <!-- 元信息 -->
        <view class="flex justify-between text-[22rpx] text-[#999] mb-[18rpx]">
          <!-- <view>开始时间：{{ item.start_date }}</view> -->
          <view>截止时间：{{ item.deadline }}</view>
        </view>
      </view>
    </view>

    <!-- 底部操作 -->
    <view v-if="item.status != 5" class="flex items-center justify-end w-full mt-[10rpx] pt-[10rpx] border-t border-[#f5f7fa] gap-[12rpx] flex-wrap">
      <!-- 动态操作按钮 -->
      <template v-for="action in getActionList()" :key="action">
        <nut-button size="small" :type="getButtonType(action)" @click.stop="handleAction(action)" class="">
          {{ action }}
        </nut-button>
      </template>
    </view>

    <!-- 支付方式选择弹窗 -->
    <PaymentMethodModal 
      v-model="showPaymentModal" 
      :amount="parseFloat(props.item.total_amount || '0')"
      @confirm="handlePaymentConfirm"
      @cancel="handlePaymentCancel"
    />
  </view>
</template>

<script setup>
import { computed, ref } from "vue";
import { IconFont } from "@nutui/icons-vue-taro";
import { Button as nutButton } from "@nutui/nutui-taro";
import dayjs from "dayjs";
import Taro from "@tarojs/taro";
import { post } from "@/utils/request";
import PaymentMethodModal from "@/components/PaymentMethodModal.vue";
import { useUserStore } from "@/store/user";

const statusMap = {
  1: "招聘中",
  2: "停止招聘",
  3: "已取消",
  4: "已完成",
};

//获取操作按钮列表方法
const getActionList = () => {
  if (props.item.pay_status == 0) {
    if(props.item.abort == 0){
      return ["支付费用", '取消'];
    }
    return ["支付费用"];
  }
  return ["查看申请者", "结束招聘"];
};

//获取任务状态
const getTaskStatus = () => {
  if (props.item.status == 5) {
    return "已取消";
  }
  if (props.item.pay_status == 0) {
    return "待发布";
  }
  return "招聘中";
};

/**
 * 获取按钮类型
 * @param {string} action - 操作名称
 * @returns {string} 按钮类型
 */
const getButtonType = (action) => {
  switch (action) {
    case "支付费用":
      return "warning";
    case "取消":
      return "default";
    case "查看申请者":
      return "info";
    case "结束招聘":
      return "danger";
    default:
      return "default";
  }
};

const props = defineProps({
  item: {
    type: Object,
    required: true,
    default: () => ({
      jobTitle: "", // 岗位名称
      status: "", // 招聘中/已结束
      statusClass: "",
      dailySalary: "", // 日薪
      workLocation: "", // 工作地点
      workDate: "", // 工作日期
      //applyCount: 0, // 报名人数
      hireCount: 0, // 录用人数
      //remaining: 0, // 剩余名额
      publishTime: "", // 发布时间
      deadline: "", // 截止时间
      isExpiring: false, // 是否即将截止
      description: "",
    }),
  },
});

//状态转换方法
const change = (item) => {
  console.log("item为", item);
  // item.releaseStatus 发布状态，招聘、日结类：1 待支付 2 审核中 3 审核通过 4 审核不过 5 停止招聘
  if (item.releaseStatus) {
    switch (item.releaseStatus) {
      case 1:
        return "待支付";
      case 2:
        return "审核中";
      case 3:
        return "招聘中";
      case 4:
        return "审核不过";
      case 5:
        return "停止招聘";
      default:
        break;
    }
  }

  // 检查招聘是否已取消
  switch (item) {
    case 1:
      return "招聘中";
    case 2:
      return "停止招聘";
    case 5:
      return "已取消";
    case 4:
      return "已完成";
    case 21:
      return "待审核";
    case 22:
      return "确认完成";
    case 23:
      return "有纠纷";
    case 24:
      return "纠纷协商";
    default:
      return "未知状态";
  }
};

const emit = defineEmits([
  "viewDetails",
  "edit",
  "endRecruit",
  // 新增事件
  "viewApplicants",
  "editRecruitment",
  "endRecruitment",
  "deleteRecruitment",
  "applyRecruitment",
  "cancelApplication",
  "cancel",
  "refresh",
]);

// 用户store
const userStore = useUserStore();

// 支付方式选择弹窗相关
const showPaymentModal = ref(false);

/**
 * 处理操作按钮点击
 * @param {string} action - 操作名称
 */
const handleAction = (action) => {
  console.log("执行操作:", action, props.item);

  // 根据操作名称触发对应事件
  switch (action) {
    case "支付费用":
      showPaymentModal.value = true;
      break;
    case "取消":
      emit("delete", props.item);
      break;
    case "查看申请者":
      emit("viewApplicants", props.item);

      Taro.navigateTo({
        url: `/pages/post/applicants?taskId=${props.item.id}&type=daily`,
      });
      break;
    case "结束招聘":
      emit("delete", props.item);
      break;
    default:
      console.warn("未知操作:", action);
  }
};

// 保留原有的事件处理函数（向后兼容）
const handleViewDetails = () => emit("viewDetails", props.item);
const handleEdit = () => emit("edit", props.item);
const handleEndRecruit = () => emit("delete", props.item);

/**
 * 微信支付处理
 * @param {Object} param - 支付参数
 */
const doPay = (param) => {
  window.WeixinJSBridge.invoke(
    "getBrandWCPayRequest",
    {
      appId: param.appid, //公众号ID，由商户传入
      timeStamp: param.timeStamp, //时间戳，自1970年以来的秒数
      nonceStr: param.nonceStr, //随机串
      package: param.prepayId,
      signType: "RSA", //微信签名方式：
      paySign: param.paySign, //微信签名
    },
    function (param) {
      if (param.err_msg === "get_brand_wcpay_request:ok") {
        // 使用以上方式判断前端返回,微信团队郑重提示：
        //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠，商户需进一步调用后端查单确认支付结果。
        Taro.showToast({
          title: "支付成功！",
          icon: "success",
          duration: 2000,
        });
      } else {
        Taro.showToast({ title: "支付失败！", icon: "error", duration: 2000 });
      }
      // 支付后刷新列表数据（2秒后执行，等待提示消失）
      setTimeout(() => {
        emit('refresh');
      }, 1200);
    }
  );
};

/**
 * 处理支付方式确认
 * @param method 支付方式
 */
const handlePaymentConfirm = async (method) => {
  try {
    // 调用支付接口
    const payRes = await post("/pay/recruitmentDaily", {
      amount: props.item.total_amount,
      bid: props.item.id,
      vipType: 1,
      deductionBalance: method === 'balance' ? 1 : 0, // 余额支付传1，微信支付传0
    });

    console.log("payRes5 --->>>", payRes);

    if (payRes.code == 0) {
      if (method === 'wechat') {
        // 微信支付
        doPay(payRes.data);
      } else {
        if(payRes.data.code == 2){
        // 余额支付
        Taro.showToast({
          title: "支付成功！",
          icon: "success",
          duration: 2000,
        });
        // 更新用户余额
        const newBalance = (userStore.userInfo.balance || 0) - parseFloat(props.item.dailySalary || '0');
        userStore.updateBalance(newBalance);
        // 刷新页面数据
        setTimeout(() => {
            emit('refresh', props.item);
          }, 2000);
        }
        else{
          Taro.showToast({
            title: payRes.data.msg || "支付失败",
            icon: "none",
            duration: 2000,
          });
        }
      }
    } else {
      Taro.showToast({
        title: payRes.message || "支付失败",
        icon: "error",
        duration: 2000,
      });
    }
  } catch (error) {
    console.error("支付失败:", error);
    Taro.showToast({
      title: "网络错误，请重试",
      icon: "error",
      duration: 2000,
    });
  }
};

/**
 * 处理支付取消
 */
const handlePaymentCancel = () => {
  // 阻止事件冒泡，避免触发父组件的点击事件
  showPaymentModal.value = false;
  Taro.showToast({
    title: "已取消支付",
    icon: "none",
  });
};

/**
 * 支付招聘费用（保留原函数用于兼容，已废弃）
 */
// const handlePay = async () => {
//   try {
//     const payRes = await post("/pay/recruitmentDaily", {
//       amount: props.item.dailySalary,
//       bid: props.item.id,
//       vipType: 1,
//     });
//     if (payRes.code == 0) {
//       doPay(payRes.data);
//     } else {
//       Taro.showToast({
//         title: payRes.message || "支付失败",
//         icon: "error",
//         duration: 2000,
//       });
//     }
//   } catch (error) {
//     console.error("支付失败:", error);
//     Taro.showToast({
//       title: "网络错误，请重试",
//       icon: "error",
//       duration: 2000,
//     });
//   }
// };
</script>
